import {PureComponent} from 'react';

class FormSubmit extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            formValues: {},
            files: [
                {value: 1, text: 'One', checked: false},
                {value: 2, text: 'Two', checked: false},
                {value: 3, text: 'Three', checked: false}
            ]
        }
    }
    valueChange = function(event) {
        const {formValues} = this.state;
        formValues[event.target.name] = event.target.value;
        this.setState({
            formValues: formValues
        })
    }
    submit = function(event) {
        console.log(this.state.formValues);
    }
    checkboxChange = function(e, i) {
        const {formValues} = this.state;
        const files = [...this.state.files];
        files[i].checked = e.target.checked;
        console.log('target', e.target, files)
        formValues.filesValue = files.filter(f => f.checked).map(f => f.value)
        this.setState({
            files: files,
            formValues: formValues
        })

    }

    render() {
        const {formValues, files} = this.state;
        return (
            <div>
                <div>
                    <label htmlFor="username" className="form-label">
                        用户名：<input value={formValues.username} id='username' name='username' onChange={v => this.valueChange(v)}/>
                    </label>
                    <div>
                        {
                            files.map((f, i) => (
                                <label key={f.value} htmlFor={f.text}>
                                    <input type="checkbox" checked={f.checked} id={f.text} value={f.value} onChange={e => this.checkboxChange(e, i)}/>
                                    {f.text}
                                </label>
                            ))
                        }
                    </div>
                    <button type="submit" onClick={e => this.submit(e)}>Submit</button>
                </div>
            </div>
        )
    }
}
export default FormSubmit